package com.wly.mina.filter;

import java.util.logging.Logger;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolDecoder;
import org.apache.mina.filter.codec.ProtocolDecoderOutput;

import com.wly.packet.Packet;
import com.wly.packet.PacketFactory;

public class GPBDecoder implements ProtocolDecoder
{

	private static Logger log = Logger.getLogger("GPBDecoder");
	@Override
	public void decode(IoSession session, IoBuffer buff, ProtocolDecoderOutput out)
			throws Exception
	{
//		log.info(buff.toString());
	
		int contentLen = (int)buff.getShort();
		int type       = (int)buff.getShort();
		System.out.println("get message head:"+contentLen+" "+type);
		if(contentLen != buff.remaining())
		{
			log.info("do not have enough data");
			return;
		}
		int i = 0;
		byte[] bytearr = new byte[contentLen];
		while(buff.hasRemaining())
		{
			bytearr[i++] = buff.get();
		}
		Packet packet = PacketFactory.getInstance().decodeObject(type, bytearr);
		out.write(packet);
	}

	@Override
	public void dispose(IoSession arg0) throws Exception
	{
		// TODO Auto-generated method stub

	}

	@Override
	public void finishDecode(IoSession session, ProtocolDecoderOutput out)
			throws Exception
	{
	}

}
